/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EstadoZonas.java
 *
 * Created on 29-jul-2012, 16:28:45
 */
package megamar;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import reportes.MetodosImpresion;
/**
 *
 * @author Lizondo1
 */
public class EstadoZonas extends javax.swing.JDialog {

    /** Creates new form EstadoZonas */
    public EstadoZonas(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        cargartabla();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaestadozona = new javax.swing.JTable();
        jbimprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Listado general de Zonas");

        tablaestadozona.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tablaestadozona.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaestadozonaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaestadozona);

        jbimprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/printer_48.png"))); // NOI18N
        jbimprimir.setText("Imprimir Estado de Zona");
        jbimprimir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jbimprimir.setEnabled(false);
        jbimprimir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbimprimir.setIconTextGap(1);
        jbimprimir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbimprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbimprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbimprimir)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, 0, 558, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbimprimir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbimprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbimprimirActionPerformed
        /*
         * Cuando se imprime el formulario "Estado de Zona" se registra:
         * numero de recibos cortados, estado de la zona y total a cobrar por el cobrador.
         * Estos datos sirven para calcular luego la liquidacion de los cobradores.
         */
        int fila = tablaestadozona.getSelectedRow();
        String idzona = String.valueOf(tablaestadozona.getValueAt(fila, 0));
        String zona = String.valueOf(tablaestadozona.getValueAt(fila, 1));
        String num_recibos = String.valueOf(tablaestadozona.getValueAt(fila, 2));
        String estado_zona = String.valueOf(tablaestadozona.getValueAt(fila, 3));
        String total_cobrar = String.valueOf(tablaestadozona.getValueAt(fila, 4));

        String consulta = "UPDATE zona "
                + "SET num_recibos = '" + num_recibos + "', estado_zona='" + estado_zona + "', total_cobrar='" + total_cobrar + "' "
                + "WHERE idzona='" + idzona + "'";
        try {
            Conectar();
            int done = stmt.executeUpdate(consulta);
            JOptionPane.showMessageDialog(null, "Se actualizaron los datos del estado de la Zona.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            db.close(stmt);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error al actualizar los datos del estado de la Zona.", JOptionPane.ERROR_MESSAGE);
        }
        
        consulta = "SELECT count(*) as rows, sum(c.saldo) as saldo, sum(c.cuota) as cuota "
                + "FROM credito c, cliente x, zona z "
                + "WHERE c.estado='DEBE' and c.idcliente=x.idcliente and z.idzona=x.idzona and x.idzona = '" + idzona + "'";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            
            while (rs.next()) {
                estado_zona = rs.getString("saldo");
                total_cobrar = rs.getString("cuota");
                num_recibos = rs.getString("rows");
            }
            db.close(stmt);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error al actualizar los datos del estado de la Zona.", JOptionPane.ERROR_MESSAGE);
        }
                
        try {
            new MetodosImpresion().ReporteEstadoZona(zona, estado_zona, total_cobrar, num_recibos);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(EstadoZonas.class.getName()).log(Level.SEVERE, null, ex);
        }catch (SQLException ex) {
            Logger.getLogger(EstadoZonas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbimprimirActionPerformed

    private void tablaestadozonaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaestadozonaMouseClicked
        jbimprimir.setEnabled(true);
    }//GEN-LAST:event_tablaestadozonaMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EstadoZonas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EstadoZonas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EstadoZonas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EstadoZonas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                EstadoZonas dialog = new EstadoZonas(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbimprimir;
    private javax.swing.JTable tablaestadozona;
    // End of variables declaration//GEN-END:variables
    private conexion db;
    private Statement stmt;
    
    public void Conectar() {
        try {
            db = new conexion();      //instancia de la clase conexion.java
            db.init();
            Connection conn = db.getMyConnection();
            stmt = conn.createStatement();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void cargartabla() {
        String consulta ="SELECT distinct(x.idzona), z.descripcion as 'Zona', count(c.idcredito) as 'Cant. de Recibos', sum(c.compra_total) as 'Estado',sum(c.cuota) as 'Total a Cobrar' "
                + "FROM credito c, cliente x, zona z "
                + "WHERE c.estado ='DEBE' and c.idcliente=x.idcliente and z.idzona=x.idzona "
                + "GROUP BY x.idzona";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            DefaultTableModel modelo = new DefaultTableModel();
            tablaestadozona.setModel(modelo);
            ConversorRSaDefaultTableModel.completar(rs, modelo);
            //codigo para ocultar la primera columna (idplan)
            tablaestadozona.getColumnModel().getColumn(0).setMaxWidth(0);
            tablaestadozona.getColumnModel().getColumn(0).setMinWidth(0);
            tablaestadozona.getColumnModel().getColumn(0).setPreferredWidth(0);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,ex.getMessage(), "Error al cargar la tabla de Creditos de Clientes.", JOptionPane.ERROR_MESSAGE);
        }
    }
}
